<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="user_votes")
 */
class UserVotes extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\User_votes();

        $this->assign('getStatusList', $this->model->getStatusList());

    }




    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k => $val) {
                $code = json_decode($val['code'],true);
                foreach ($code as $k1 => $val1) {
                    $val['codetitle'] = $val['codetitle'] . $val1['code'] . ",";
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();
        $tableName = $this->model->getName();
        $tableName = CommonTool::humpToLine(lcfirst($tableName));
        $prefix = config('database.connections.mysql.prefix');
        $dbList = Db::query("show full columns from {$prefix}{$tableName}");
        $header = [];
        foreach ($dbList as $vo) {
            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
            if (!in_array($vo['Field'], $this->noExportFields)) {
                $header[] = [$comment, $vo['Field']];
            }
        }
        $list = $this->model
            ->where($where)
            ->limit(100000)
            ->order('id', 'desc')
            ->select()
            ->toArray();
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) {
            $this->error('数据不存在');
        }
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

    public function get_total()
    {
        $ip_num = $this->model
            ->where('status', '=', 1)
            ->count();
        $captcha_num = (new \app\admin\model\UserCaptcha())
            ->where('status', '=', 1)
            ->count();
        $err_num = (new \app\admin\model\LoginLog())
            ->where('err_num', '>', 0)
            ->count();
        $fireclose = sysconfig('fire','fire_close');

        $data = [
            'code'  => 1,
            'msg'   => 'ok',
            'fireclose' => $fireclose,
            'ip_num'  => $ip_num,
            'captcha_num'  => $captcha_num,
            'err_num'  => $err_num,
        ];
        return json($data);
    }

    public function fire_colse()
    {

        $fireclose = sysconfig('fire','fire_close');
        $fireclose = ($fireclose == 1) ? 2 : 1;
          (new \app\admin\model\SystemConfig())
            ->where('name', '=', 'fire_close')
            ->update(['value' => $fireclose]);

        $this->close_fire($fireclose);
        $data = [
            'code'  => 1,
            'msg'   => $fireclose == 1 ? '开启成功' :"关闭成功",
            'fireclose' => $fireclose,
        ];
        return json($data);
    }

    private function get_ipdizhi($ip)
    {
       $url = "http://apis.juhe.cn/ip/ipNew?ip=".$ip."&key=8fbdf22f2872b41fcd5aa8c9d4556507";
        return json_decode($this->curl_get($url),true);
    }

    /**
     * php后台get提交 阻塞
     * @param $url
     * @param int $httpCode
     * @return bool|string
     */
    private  function curl_get($url,$type="json"){
        $curl = curl_init();
        if ($type == "json"){
            $headers = array("Content-type: application/json;charset=UTF-8");
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);

        return $output;
    }



}